#include "config.h"
#include <QDebug>
Config::Config()
{

}

Config::~Config()
{
    save();
}

int Config::open(const QString &filename)
{
    m_file = filename;

    QFile f(m_file);
    if(f.exists())
    {
        if(f.open(QIODevice::ReadOnly))
        {
           QByteArray ba= f.readAll();
           if(ba.length() > 0)
           {
               QJsonParseError err;
               QJsonDocument m_jsonDoc = QJsonDocument::fromJson(ba,&err);
               if(err.error == QJsonParseError::NoError)
               {
                   m_jsonRoot= m_jsonDoc.object();

               }
           }
           f.close();
        }

    }
    return 0;
}

void Config::setParam(const QString &name, const QString &value)
{
    if(getParam(name) != value)
    {
        QJsonValue val(value);
        m_jsonRoot.insert(name,val);

        save();
    }
}

void Config::setInt(const QString &name, int value)
{
    if(getInt(name) != value)
    {
        QJsonValue val(value);
        m_jsonRoot.insert(name,val);

        save();
    }
}

void Config::setBool(const QString &name, bool value)
{
    if(getBool(name) != value)
    {
        QJsonValue val(value);
        m_jsonRoot.insert(name,val);

        save();
    }
}

QString Config::getParam(const QString &name)
{
    QString ret;
    QJsonValue val=m_jsonRoot.value(name);
    if(val.isString())
    {
        ret= val.toString();
    }

    return ret;
}
int Config::getInt(const QString &name)
{
    QJsonValue val=m_jsonRoot.value(name);
    if(val.isDouble())
    {
        return (int)val.toDouble();
    }

    return 0;
}

bool Config::getBool(const QString &name)
{
    QJsonValue val=m_jsonRoot.value(name);
    if(val.isBool())
    {
        return val.toBool();
    }

    return false;
}

void Config::save()
{
    QJsonDocument jsonDoc;
    jsonDoc.setObject(m_jsonRoot);
    QByteArray ba= jsonDoc.toJson();

    if(m_file.length() > 1 && ba.length() > 0)
    {
        QFile wf(m_file);
        if(wf.open(QIODevice::WriteOnly))
        {
            wf.write(ba.data(),ba.length());
            wf.close();
        }
    }
}
